package org.SimpleSpringBoot;

import org.SimpleSpringBoot.annotation.SimpleSpringBootApplication;
import org.SimpleSpringBoot.container.ApplicationContext;
import org.SimpleSpringBoot.web.SimpleWebServer;

/**
 * 简化版springboot启动器
 */
public class SimpleSpringBootRunner {

/**
 * 运行springboot应用
 */
public static ApplicationContext run(Class<?> primarySource,String...args) {
    System.out.println("简化版springboot应用");
    System.out.println("主类启动："+primarySource.getName());

    //验证启动类
    if (!primarySource.isAnnotationPresent(SimpleSpringBootApplication.class)){
        throw new IllegalArgumentException("启动类必须使用SimpleSpringBootApplication注解");
    }
    long startTime = System.currentTimeMillis();
    try{
        //创建应用上下文
        ApplicationContext applicationContext = new ApplicationContext(primarySource);
        long endTime = System.currentTimeMillis();
        System.out.println("应用启动完成，耗时"+(endTime-startTime)+"ms");

        //注册关闭钩子
        registerShutdownHook(applicationContext);
        return applicationContext;
    }catch (Exception e){
        System.out.println("应用启动失败"+e.getMessage());
        e.printStackTrace();
        throw new RuntimeException("应用启动失败"+e);
    }
}

    /**
     * 注册关闭钩子
     * @param applicationContext
     */
    private static void registerShutdownHook(ApplicationContext applicationContext) {
    Runtime.getRuntime().addShutdownHook(new Thread(()-> {
            System.out.println("应用正在关闭。。。");

            //停止web服务器
            try {
                if (applicationContext.containsBean("webServer")){
                    Object webServer = applicationContext.getBean("webServer");
                    if (webServer instanceof SimpleWebServer){
                        ((SimpleWebServer) webServer).stop();
                    }
                }
            }catch (Exception e){
                System.out.println("关闭web服务器时发生错误"+e.getMessage());
            }
            System.out.println("应用已经关闭");
        }));
    }
}
